package org.itsky.consumer;

import org.itsky.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.sound.midi.Soundbank;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author sky
 * @Site cmtianxie163.com 2020/4/2 10:32
 */
@RestController
public class UseHelloController {
    @GetMapping("/hello1")
    public String hello1(){
        HttpURLConnection con = null;
        try {
            URL url = new URL("http://localhost:1113/hello");
            con = (HttpURLConnection) url.openConnection();
            if(con.getResponseCode() == 200){
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String s = br.readLine();
                br.close();
                return s;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    @Qualifier("restTemplateOne")
    RestTemplate restTemplateOne;
    @GetMapping("hello2")
    public String hello2() {
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        ServiceInstance instance = list.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        StringBuffer sb = new StringBuffer();
        sb.append("http://")
                .append(host)
                .append(":")
                .append(port)
                .append("/hello");
//        HttpURLConnection con = null;
//        try {
//            URL url = new URL(sb.toString());
//            con = (HttpURLConnection)url.openConnection();
//            if (con.getResponseCode() == 200){
//                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
//                String s = br.readLine();
//                br.close();
//                return s;
//            }
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "error";
        String s = restTemplateOne.getForObject(sb.toString(), String.class);
        return s;
    }

    int count = 0;
    @GetMapping("hello3")
    public String hello3() {
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        ServiceInstance instance = list.get((count++)%list.size());
        String host = instance.getHost();
        int port = instance.getPort();
        StringBuffer sb = new StringBuffer();
        sb.append("http://")
                .append(host)
                .append(":")
                .append(port)
                .append("/hello");
        HttpURLConnection con = null;
        try {
            URL url = new URL(sb.toString());
            con = (HttpURLConnection)url.openConnection();
            if (con.getResponseCode() == 200){
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String s = br.readLine();
                br.close();
                return s;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 注入的restTemplate 上加入了 @LoadBalanced注解
     * 就自动具备了负载均衡的功能
     */
    @Autowired
    @Qualifier("restTemplate")
    RestTemplate restTemplate;
    @GetMapping("/hello4")
    public String hello4(){
        return restTemplate.getForObject("http://provider/hello",String.class);
    }

    @GetMapping("hello5")
    public String hello5(){
        String s = restTemplate.getForObject("http://provider/hello2?name={1}", String.class, "chengming");
        System.out.println(s);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://provider/hello2?name={1}", String.class, "jinchengming");
        String body = responseEntity.getBody();
        System.out.println("body" + body);
        HttpStatus statusCode = responseEntity.getStatusCode();
        System.out.println("statusCode " + statusCode);
        int statusCodeValue = responseEntity.getStatusCodeValue();
        System.out.println("statisCodeValue " + statusCodeValue);

        HttpHeaders headers = responseEntity.getHeaders();
        Set<String> strings = headers.keySet();
        for (String string : strings) {
            System.out.println(string + "--" + headers.get(string));
        }

        return s;

    }

    @GetMapping("/hello6")
    public void hello6() throws UnsupportedEncodingException {
        //第一种
        String s1 = restTemplate.getForObject("http://provider/hello2?name={1}", String.class, "jin");
        System.out.println(s1);

        //第二种
        Map<String,Object> map = new HashMap<>();
        map.put("name","chengming");
        String s2 = restTemplate.getForObject("http://provider/hello2?name={name}", String.class, map);
        System.out.println(s2);

        //第三种
        String url = "http://provider/hello2?name="+ URLEncoder.encode("成名", "UTF-8");
        URI uri = URI.create(url);
        String s3 = restTemplate.getForObject(uri, String.class);
        System.out.println(s3);
    }


    /**
     * 如果post 是key/value形式传参 则第二个参数是MutiValueMap
     * 如果是json形式传参 则第二个参数是 普通对象
   */
    @GetMapping("/hello7")
    public void hello7(){
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("id",1);
        map.add("username","jinchengming");
        map.add("password","123");
        User user = restTemplate.postForObject("http://provider/user1", map, User.class);
        System.out.println(user);
        System.out.println("-----------------------");
        user.setId(2);
        user.setUsername("heling");
        User user1 = restTemplate.postForObject("http://provider/user2", user, User.class);
        System.out.println(user1);
    }

    /**
     * 有的时候当执行一个post请求之后，立马要进行重定向 比如注册 当注册完成后，立马重定向到登录页面去登录
     * 对于这种场景，就可以使用postForLocation.
     */

    @GetMapping("/hello8")
    public void hello8(){
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("id",11);
        map.add("username","jin");
        map.add("password",12123);
        URI uri = restTemplate.postForLocation("http://provider/register", map);
        System.out.println(uri);

        String s = restTemplate.getForObject(uri, String.class);
        System.out.println(s);
    }

    @GetMapping("/hello9")
    public void hello9(){
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("id",22);
        map.add("username","ming");
        map.add("password",111);
        restTemplate.put("http://provider/user1",map);
        User user = new User();
        user.setId(99);
        user.setUsername("jcm");
        user.setPassword("13345");
        restTemplate.put("http://provider/user2",user);

    }
}
